$(function(){
    
    $.ajax({
        url:'./data/goods.json',
        type:'get',
        dataType:'json',
        success:function(data){
            var strDom = ''
            $.each(data,function(index,item){
                var goods = `
            <div class="goods">
                <img src="${item.imgurl}" alt="">
                <p>${item.price}</p>
                <h3>${item.title}</h3>
                <span>${item.suggest}</span>
                <div data-id="${item.id}">>>加入购物车</div>
            </div>
                `
                strDom+=goods
            })
            $('.content').html(strDom)
        }
    })
   
    if(localStorage.getItem('goods')){
        var goodsArr = JSON.parse(localStorage.getItem('goods'))
    }else{
        var goodsArr = []
    }
    console.log(goodsArr)
    $('.content').on('click','.goods div',function(){
        var id = $(this).attr('data-id')
        var flag = false
        $.each(goodsArr,function(index,item){
            if(item.id === id){
                item.num++
                flag = true
            }
        })
        if(!flag){
            goodsArr.push({'id':id,'num':1})
        }
        localStorage.setItem('goods',JSON.stringify(goodsArr))
        alert('加入购物车成功！')
    })


})